<?php
/**                                          
 * 名人堂
 * @author M2
 * @version 1.0
 * create Date 2013-04-27
 */
class StarModel extends Model {
	protected $tableName = 'weibo_star';
	protected $group_list;
	/**
	 * 获取某一父级分组下的子级分组列表
	 * @param int $tid 父级分组ID
	 */
	public function getGroupList($tid=0){
		$map['top_group_id'] = intval($tid);
		$list = M('weibo_star_group')->where($map)->order('display_order ASC,star_group_id DESC')->select();
		if(empty($this->group_list)){
			if($tid==0){
				$this->group_list = $list;
			}else{
				$this->group_list[] = array('star_group_id'=>$tid,'son_list'=>$list);
			}
		}
		return $list;
	}

	/**
	 * 获取当前分组的所有子分组	
	 */
	public function getAllGroupList(){
		if ( ($cache = S('Cache_Star_Group')) != false ) {
			$this->group_list = $cache;
			return $this->group_list;
		}
		if(empty($this->group_list)) {
			$this->getGroupList();
		}
		foreach($this->group_list as &$v){
			$v['son_list'] = $this->getGroupList($v['star_group_id']);
		}
		S('Cache_Star_Group',$this->group_list);
		return $this->group_list;
	}

	/**
	 * 按分组获取名人列表	
	 * @param int $limit 显示条数
	 */
	public function getStarsByGroup($limit=6){
		if(empty($this->group_list)){
			$this->getAllGroupList();
		}
		$group_list = $this->group_list;
		$limit = intval($limit);
	
		foreach($group_list as $k=>&$v){
			$v['user_list'] = $this->getStarsCache($v['star_group_id'],$limit);
			if(!empty($v['son_list']) && is_array($v['son_list'])){
				foreach($v['son_list'] as $ks=>&$vs){
					$vs['user_list'] =  $this->getStarsCache($vs['star_group_id'],$limit);
					if(!$vs['user_list'])unset($v['son_list'][$ks]);
				}
			}
			if(!$v['user_list'] && !$v['son_list'])unset($group_list[$k]);
		}

		return $group_list;
	}

	/**
	 * 获取缓存信息
	 * @param int $star_group_id 名人堂分组ID
	 * @param int $limit 显示条数
	 * @param boolean $refresh 缓存是否设置
	 */
	public function getStarsCache($star_group_id,$limit=10, $refresh = false){
		if(($cache = S('Cache_Weibo_Star_'.$star_group_id)) === false || true == $refresh){
    		S('Cache_Weibo_Star_t_'.$star_group_id,time()); //缓存未设置 先设置缓存设定时间	
    	}else{
    		if(($cacheSetTime =  S('Cache_Weibo_Star_t_'.$star_group_id)) === false || $cacheSetTime+600 <= time()){
    			S('Cache_Weibo_Star_t_'.$star_group_id,time()); //缓存未设置 先设置缓存设定时间	
    		}else{
    			return !empty($limit) ? array_slice($cache,0,$limit) : $cache;
    		}
    	}	
		$map['star_group_id'] = $star_group_id;
		$cache = $this->where($map)->order('star_id DESC')->select();
		S('Cache_Weibo_Star_'.$star_group_id,empty($cache) ? array() : $cache);
		
		return !empty($limit) ? array_slice($cache,0,$limit) : $cache;
	}
	
	/**
	 * 获取所有名人堂信息	
	 */
	public function getAllStart() {
		$cache_id = '_weibo_star_model_all_star';
		if (($res = F($cache_id)) === false) {
			$res = $this->field('DISTINCT(uid)')->select();
			F($cache_id, $res);
		}
		return $res;
	}
}